package com.huaixia18.systemnotice.service;

import com.huaixia18.systemnotice.domain.ManagerSystemNotice;
import com.huaixia18.systemnotice.domain.UserSystemNotice;
import com.huaixia18.systemnotice.mapper.ManagerSystemNoticeMapper;
import com.huaixia18.systemnotice.mapper.UserSystemNoticeMapper;
import lombok.AllArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
@AllArgsConstructor
public class SystemNoticeService  {

    @Autowired
    private ManagerSystemNoticeMapper managerSystemNoticeMapper;
    @Autowired
    private UserSystemNoticeMapper userSystemNoticeMapper;

    public void publishSystemNotice(ManagerSystemNotice notice) {
        managerSystemNoticeMapper.insert(notice);

    }

    public List<UserSystemNotice> getUserSystemNotices(Long recipientId) {
        return userSystemNoticeMapper.findByRecipientIdAndState(recipientId, false);
    }

    // 系统定时拉取通知并插入用户系统通知表
    public void pullSystemNotices() {
        List<ManagerSystemNotice> notices = managerSystemNoticeMapper.findByType("all");
        for (ManagerSystemNotice notice : notices) {
            if (!notice.isState()) {
                List<UserSystemNotice> userNotices = userSystemNoticeMapper.findByRecipientIdAndState(notice.getRecipientId(), false);
                if (userNotices.isEmpty()) {
                    UserSystemNotice userNotice = new UserSystemNotice();
                    userNotice.setSystemNoticeId(notice.getId());
                    userNotice.setRecipientId(notice.getRecipientId());
                    userNotice.setState(false);
                    userSystemNoticeMapper.insert(userNotice);
                }
                notice.setState(true);
                managerSystemNoticeMapper.insert(notice);
            }
        }
    }

}
